import wave
import ossaudiodev
import threading

class Record(threading.Thread):
	def __init__(self, device='/dev/dsp'):
		self.play = True
		self.device = device
	 	self.recString = ''
	 	self.playString = ''
	 	self.CHANNELS = 1
	 	self.RATE = 100000
	 	self.FORMAT = ossaudiodev.AFMT_S16_LE
	 	threading.Thread.__init__(self)
	 	
	def __record(self):
		return self.dsp.read(1024)
	
	def gravar(self):
		self.__configuraDsp('r')
		self.play = True
		self.start()
		
	def __configuraDsp(self,tipo):
		self.dsp = ossaudiodev.open(self.device,tipo)
		self.dsp.setfmt(self.FORMAT)
		self.dsp.speed(self.RATE)
		self.dsp.channels(self.CHANNELS)
		
	def parar(self):
		self.play = False
		self.dsp.close()
		
	def tocar(self):
		self.__configuraDsp('w')
		self.dsp.write(self.playString)
		self.dsp.close()
		
	def run(self):
		self.recString = ''
		while self.play:
			self.recString = self.recString + self.__record()
			
		
		
	def save2raw(self,nomeSaida = 'output.raw'):
		raw = open(nomeSaida,'wb')
		raw.write(self.recString)
		raw.close()
		
	def tocarRaw(self, nomeEntrada = 'output.raw'):
		raw = open(nomeEntrada,'r')
		self.playString = raw.read()
		self.tocar()
		
	def tocarGravacao(self):
		self.playString = self.recString
		self.tocar()
	
	def save2wave(self,nomeSaida = "output.wav"):
		wf = wave.open(nomeSaida, 'wb')
		wf.setnchannels(self.CHANNELS)
		wf.setsampwidth(2)
		wf.setframerate(self.RATE)
		wf.setcomptype("NONE", "Uncompressed")
		wf.writeframes(self.recString)
		wf.close()
		
	def tocarWave(self,nomeWave):
		wav = wave.open(nomeWave)
		self.playString = wav.readframes(wav.getnframes())
		self.tocar()
		
########################################################
###########					TESTER					###########

if __name__=='__main__':
	
	record = Record('/dev/dsp')
	print "Gravando..."
	record.gravar()
	raw_input("\nTecle ENTER para PARAR a gravacao")
	record.parar()
	raw_input("\nTecle ENTER para ouvir a gravacao")
	record.tocarGravacao()
	record.save2wave('audio/testeAtraso.wav')
	#record.save2raw()
	#raw_input("\nTecle ENTER para ouvir o wave")
	#record.tocarWave('output.wav')
